import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;

/**
 * Represents a User with a name and StatsList
 *
 */
public class User 
{
	private StatsList statsList;
	private DateList  dateList;
	private String name;
	/**
	 * The current User of the program.
	 */
	
	/**
	 * Creates a User With a Specified name 
	 * @param name the new User's name
	 */
	public User(String name)
	{
		this.name= name;
		statsList= new StatsList();
		dateList= new DateList();
	}
	
	/**
	 * Adds a game to the User's StatsList and dateList
	 * @param addition the SubitizePanel to add
	 */
	public void addGame(SubitizePanel addition)
	{
		statsList.addGame(addition);
		dateList.addDateNode(addition);
	}
	
	public StatsList getStatsList() 
	{
		return statsList;
	}
	
	public DateList getDateList()
	{
		return dateList;
	}

	public String getName() 
	{
		return name;
	}
	
	/**
	 * saves the user to a file name.dat where name is the name of the user
	 * the file contains the String created by statsList.toString();
	 * @throws IOException
	 */
	public void save() throws IOException
	{
		String data= statsList.toString()+dateList.toString();
		PrintWriter writer= new PrintWriter(new FileWriter(name+".dat"));
		writer.println(data);
		writer.close();
	}
	
	/**
	 * Reverses save() loads a user from a file.
	 * 
	 * @param name the name of the user, not the file name.
	 * @return the loaded user
	 * @throws IOException
	 */
	public static User load(String name) throws IOException
	{
		BufferedReader reader= new BufferedReader(new FileReader(name+".dat"));
		String data= reader.readLine();
		reader.close();
		StatsList newStats;
		if(data==null) return new User(name);
		try
		{
			newStats= StatsList.fromString(data);
			int dateListStart= data.indexOf("f");
			String dateData= data.substring(dateListStart+1);
			DateList newDates= DateList.fromString(dateData);
			User temp= new User(name);
			temp.statsList= newStats;
			temp.dateList= newDates;
			return temp;
		}
		catch(Exception ex) // if string can't be parsed create a new user
		{
			ex.printStackTrace();
			return new User(name);
		}
	}
}
